/**
 * 冒泡排序（Bubble Sort）
 *
 * ---------------------------------
 * 文档查看: 
 * 2021-02-01
 */

const TimeTool = require('./utils/TimeTool')

function sortBubble(array) {
  if (!array) return null
  const length = array.length || 0
  if (length <= 1) return array
  for (let i = 0; i < length - 1; i ++) {
    for (let j = 0; j < length - 1 - i; j ++) {
      if (array[j] > array[j + 1]) {
        let temp = array[j]
        array[j] = array[j + 1]
        array[j + 1] = temp
      }
    }
  }
  return array
}

function sortBubble2(array) {
  if (!array) return null
  const length = array.length || 0
  if (length <= 1) return array
  for (let i = 0; i < length - 1; i ++) {
    const maxLength = length - 1 - i
    let max = 0
    for (let j = 0; j < length - 1 - i; j ++) {
      max = j + 1
      if (array[j] > array[j + 1]) {
        // let temp = array[j]
        // array[j] = array[j + 1]
        // array[j + 1] = temp
        max = j
      }

      if (max != maxLength) {
        let temp = array[max]
        array[max] = array[maxLength]
        array[maxLength] = temp
      }
    }
  }
  return array
}


// const Data = [4,3,2]
const Data = [1, 4, 9, 5, 4, 3]

const array1 = JSON.parse(JSON.stringify(Data))
TimeTool(()=> {
  console.log('\n 11 array=', array1)
  console.log(sortBubble(array1))
})

const array2 = JSON.parse(JSON.stringify(Data))
TimeTool(()=> {
  console.log('\n 22 array=', array2)
  console.log(sortBubble2(array2))
})